package com.yidianyanglao.core.handler;

import com.yidianyanglao.common.bean.ErrorLog;
import com.yidianyanglao.common.mapper.CommonMapper;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.core.util.Log;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;

public class ExceptionHandler implements HandlerExceptionResolver {

    @Resource
    private CommonMapper commonMapper;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {

        ErrorLog err = new ErrorLog(e.getMessage(), ExceptionUtils.getFullStackTrace(e),e.getClass().getName());
            Code code = Code.ERROR;
            String msg = e.getMessage();
            if (e instanceof CustomException) {
                code = ((CustomException)e).getCode();
            }
            //如果是登录超时，不记录日志
            if(!code.getNum().equals("1000")){
                commonMapper.addErrorLog(err);
            }

            try {
                PrintWriter out = response.getWriter();
                out.print("{\"retcode\":\"");
                out.print(code.getNum());
                out.print("\",\"retdesc\":\"");
                out.print(msg);
                out.print("\",\"errorid\":\"");
                out.print(err.getId());
                out.print("\"}");
            } catch (IOException e1) {
                Log.error(e.getMessage(),e1);
            }
        return new ModelAndView();
    }
}
